import React from 'react';
import { useHistory } from '../contexts/HistoryContext';

interface OutputResultProps {
  formData: {
    remarks: string;
    apiAddress: string;
    requestMethod: string;
    requestHeaders: string;
    requestBody: string;
    errorMessage: string;
  };
  setFormData: (data: OutputResultProps['formData']) => void;
}

const OutputResult: React.FC<OutputResultProps> = ({ formData, setFormData }) => {
  const { addHistory } = useHistory();

  // 处理 Markdown 图片语法
  const processContent = (content: string) => {
    const imgRegex = /!\[.*?\]\((.*?)\)/g;
    const parts = [];
    let lastIndex = 0;
    let match;

    while ((match = imgRegex.exec(content)) !== null) {
      // 添加图片前的文本
      if (match.index > lastIndex) {
        parts.push(content.slice(lastIndex, match.index));
      }
      // 添加图片元素
      parts.push(
        <img
          key={match.index}
          src={match[1]}
          alt='异常截图'
          className='max-w-full h-auto my-2 rounded shadow-lg'
        />
      );
      lastIndex = match.index + match[0].length;
    }

    // 添加剩余的文本
    if (lastIndex < content.length) {
      parts.push(content.slice(lastIndex));
    }

    return parts;
  };

  const formattedOutput = [
    formData.remarks && `${formData.remarks}`,
    formData.apiAddress && `${formData.apiAddress}`,
    formData.requestMethod,
    formData.requestHeaders && `================\n${formData.requestHeaders}`,
    formData.requestBody && `================\n${formData.requestBody}`,
    formData.errorMessage && `================\n${formData.errorMessage}`
  ]
    .filter(Boolean)
    .join('\n');

  const clearFields = () => {
    setFormData({
      remarks: '',
      apiAddress: '',
      requestMethod: '',
      requestHeaders: '',
      requestBody: '',
      errorMessage: ''
    });
  };

  const copyToClipboard = () => {
    if (!formattedOutput.trim()) return;

    navigator.clipboard.writeText(formattedOutput).then(
      () => {
        const tip = document.createElement('div');
        tip.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded shadow-lg z-50 animate-fade-out';
        tip.textContent = '复制成功！';
        document.body.appendChild(tip);
        setTimeout(() => {
          document.body.removeChild(tip);
        }, 2000);
        // 添加到历史记录
        addHistory(formData);
        // 清空表单
        clearFields();
      },
      () => {
        alert('复制失败，请手动复制。');
      }
    );
  };

  return (
    <div className='flex-[2] min-w-[400px] flex flex-col'>
      <div className='flex justify-between items-center mb-4'>
        <h1 className='text-blue-500 text-2xl font-bold'>生成结果</h1>
        <button
          className={`p-2 text-blue-500 hover:text-blue-600 hover:bg-gray-100 rounded-full transition-colors ${
            !formattedOutput.trim() ? 'opacity-50 cursor-not-allowed' : ''
          }`}
          onClick={copyToClipboard}
          title='复制到剪贴板'
          disabled={!formattedOutput.trim()}
        >
          <svg
            xmlns='http://www.w3.org/2000/svg'
            className='h-6 w-6'
            fill='none'
            viewBox='0 0 24 24'
            stroke='currentColor'
          >
            <path
              strokeLinecap='round'
              strokeLinejoin='round'
              strokeWidth={2}
              d='M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3'
            />
          </svg>
        </button>
      </div>
      <div className='flex-1 bg-gray-100 p-4 rounded border border-gray-300 whitespace-pre-wrap break-words overflow-x-auto h-[34rem] overflow-y-auto'>
        {formattedOutput ? (
          processContent(formattedOutput)
        ) : (
          <span className='text-gray-400 select-none'>在左侧输入框中填写信息后，这里将显示格式化后的内容...</span>
        )}
      </div>
    </div>
  );
};

export default OutputResult;
